//
//  DiZhenHController.swift
//  DiZhenYuJing
//
//  Created by zhibao on 2024/2/1.
//

import UIKit
import SnapKit
import SwiftSoup

@objc class DZhHomeController:SuperController,UITableViewDelegate,UITableViewDataSource,DataChangeDelegate,MKMapViewDelegate{
    
    
    //视频
    fileprivate var playItem:AVPlayerItem!
    fileprivate var playLayer:AVPlayerLayer!
    fileprivate var player:AVPlayer!
    var kvoToken: NSKeyValueObservation?
    var drawView:BoLangView!
    var drawView1:BoLangView!
    var pointArray = [CGPoint]()
    fileprivate var dataArray = [[String:Any]]()
    fileprivate var showTableView:MYTableView!
    
    //定位显示
    var locationLabel = UILabel()
    
    var appleMapView:MKMapView!
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if UserDefaults.standard.value(forKey: "privacy1") == nil {
            Helper.privacyAgreementShow()
        }
        self.getListData()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.gk_navTitleFont = MY_SCALE_BoldFont(20)
        self.gk_navTitleColor = MYBlock
        self.getPayInfo()
        self.initView()
        self.initTableView()
        self.dataArray = earthquakeData
        self.showTableView.reloadData()
        
        let twoBtn = UIButton(type: .custom)
        twoBtn.frame = CGRectMake(0, 0, pixw(p:80), pixw(p:60))
        twoBtn.addTarget(self, action: #selector(yinsiClick), for: .touchUpInside)
        twoBtn.setTitle("对话录音", for: .normal)
        twoBtn.setTitleColor(MYBlock, for: .normal)
        twoBtn.titleLabel?.font = MY_SCALE_BoldFont(15)
        let item = UIBarButtonItem(customView: twoBtn)
        self.gk_navRightBarButtonItems = [item]
       
        
        let locationImgView = UIImageView(image: Helper.image(with: MYColor.color(withHexString: "cacaca"), with: UIImage(named: "h_location")))
        self.gk_navigationBar.addSubview(locationImgView)
        locationImgView.snp.makeConstraints { make in
            make.left.equalTo(pixw(p: 10))
            make.bottom.equalTo(self.gk_navigationBar).offset(pixw(p: -4))
        }
        
        locationLabel.text = LocalizedString("定位中···")
        locationLabel.textColor = MYBlock
        locationLabel.font = MY_SCALE_BoldFont(16)
        self.gk_navigationBar.addSubview(locationLabel)
        locationLabel.snp.makeConstraints { make in
            make.left.equalTo(locationImgView.snp.right).offset(pixw(p: 3))
            make.bottom.equalTo(self.gk_navigationBar).offset(pixw(p: -7))
        }
        GetLocation.sharedManager().getLoctaion()
        GetLocation.sharedManager().getLocationBlock = {
            model in
            self.locationLabel.text = model.poiName
            MYGlobal.share().locationModel = model
            self.getListData()
        }
        
    }
    
    @objc fileprivate func yinsiClick(){
        let controller = LocAudioController()
        self.navigationController?.pushViewController(controller, animated: true)
    }
    
    fileprivate func getPayInfo(){
        if IAPShare.sharedHelper().iap == nil {
            let dataSet = NSSet(array: [
                "com.jieya.zhou",
                "com.jieya.yue",
                "com.jieya.ji",
                "com.jieya.nian",
            ])
            IAPShare.sharedHelper().iap = IAPHelper(productIdentifiers: dataSet as? Set<AnyHashable>)
        }
        IAPShare.sharedHelper().iap.requestProducts { request, response in
            DLog(message: "response1==\(String(describing: response?.products))")
        }
        IAPShare.sharedHelper().iap.production = false
    }
    fileprivate func initView(){
//        self.bgVideo()
        
        drawView = BoLangView(frame: CGRect(x: 0, y: navigationFullHeight(), width: SCREEN_WIDTH, height: pixw(p: 20)))
        drawView.backgroundColor = UIColor.clear
        drawView.colorStr = "#E04148"
        self.view.addSubview(drawView)
        drawView1 = BoLangView(frame: CGRect(x: drawView.left, y: drawView.bottom, width: drawView.width, height: drawView.height))
        drawView1.backgroundColor = UIColor.clear
        drawView1.colorStr = "#E04148"
        drawView1.transform = CGAffineTransformMakeScale(1.0, -1.0)
        self.view.addSubview(drawView1)
        
        
        for _ in 0 ..< 400 {
            let randomNumber = Int(arc4random_uniform(UInt32(drawView.height)))
            let point = CGPoint(x: drawView.height, y: Double(randomNumber))
            pointArray.insert(point, at: 0)
        }
        
        drawView.pointArray = pointArray
        drawView1.pointArray = pointArray
        
        _ = Timer.scheduledTimer(timeInterval: 0.5,
                                 target:self,selector:#selector(self.updateWater),
                                 userInfo:nil,repeats:true)
        
        //渐变
        let leftView = UIView(frame: CGRect(x: drawView.left, y: drawView.top, width: drawView.width / 2, height: drawView.height * 2))
        self.view.addSubview(leftView)
        Helper.setDiferentColors([MYColor.color(withHexString: "ffffff", alpha: 0.8).cgColor,MYColor.color(withHexString: "ffffff", alpha: 0.1).cgColor], with: leftView, withFlag: .directionLeft)
        
        let rightView = UIView(frame: CGRect(x: drawView.right - leftView.width, y: leftView.top, width: leftView.width, height: leftView.height))
        self.view.addSubview(rightView)
        Helper.setDiferentColors([MYColor.color(withHexString: "ffffff", alpha: 0.1).cgColor,MYColor.color(withHexString: "ffffff", alpha: 0.8).cgColor], with: rightView, withFlag: .directionLeft)
        
        let jkongLabel = UILabel()
        jkongLabel.text = LocalizedString("···实时监控中···")
        jkongLabel.font = MY_SCALE_BoldFont(20)
        jkongLabel.textAlignment = .center
        jkongLabel.textColor = MYRed
        self.view.addSubview(jkongLabel)
        jkongLabel.snp.makeConstraints { make in
            make.right.left.top.equalTo(drawView);
            make.bottom.equalTo(drawView1);
        }
    }
    func initTableView() {
        let top = drawView.bottom + drawView.height
        showTableView = MYTableView(frame: CGRectMake(0, top, SCREEN_WIDTH, SCREEN_HEIGHT - top - tabBarFullHeight()), style: .grouped)
        showTableView.delegate = self
        showTableView.dataSource = self
        showTableView.dataChangeDelegate = self
        showTableView.separatorStyle = .none
        showTableView.register(HomeCell.self, forCellReuseIdentifier: "HomeCell")
        self.view.addSubview(showTableView)
        showTableView.noDataType = .TableViewNoDataType_FILE
        showTableView.mj_footer?.endRefreshingWithNoMoreData()
        
        let bgView = UIView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: pixw(p: 300)))
        bgView.backgroundColor = UIColor.clear
        showTableView.tableHeaderView = bgView
        
        self.appleMapView = MKMapView(frame: CGRect(x: pixw(p: 15), y: pixw(p: 10), width: SCREEN_WIDTH - pixw(p: 30), height: pixw(p: 280)))
        self.appleMapView.layer.masksToBounds = true
        self.appleMapView.layer.cornerRadius = pixw(p: 20)
        self.appleMapView.delegate = self
        self.appleMapView.showsScale = true
        self.appleMapView.showsCompass = false
        self.appleMapView.mapType = .standard
        self.appleMapView.showsUserLocation = true
        //        mapView.setZoomLevel(5, animated: true)
        bgView.addSubview(self.appleMapView)
        
        
        addbulrEffectView(superView: self.appleMapView,title: LocalizedString("会员解锁(地图)"))
        
    }
    @objc func updateWater() {
        pointArray.removeLast()
        let randomNumber = Int(arc4random_uniform(UInt32(drawView.height)))
        let point = CGPoint(x: drawView.height, y: Double(randomNumber))
        pointArray.insert(point, at: 0)
        self.drawView.pointArray = pointArray
        self.drawView1.pointArray = pointArray
    }
}
extension DZhHomeController {
    func getListData(){
//        let paras = [String:String]()
//        HttpHelper.sharedInstance().sendCsiPost("https://www.csi.ac.cn/eportal/ui?pageId=54", parameters: paras) { tast, html in
//            QMUITips.hideAllTips()
//            self.parseHTMLWithSwiftSoup(html: html)
////            let controller = ResultDetailController()
////            controller.loadHtml = html
////            controller.type  = self.type
////            self.navigationController?.pushViewController(controller, animated: true)
//        } failure: { tast, error in
//            
//        }
//        return
        let times = TimeHelper.share().getCurrentTimeStr()
        DLog(message: "times==\(String(describing: times))")
        HttpHelper.sharedInstance().sendGet("ajax/google", parameters: ["rand":times ?? ""]) { task, model in
            DLog(message: "modell===\(String(describing: model.data))")
            let modes = model.data as! [[String : Any]]
            if modes.count < 5 {
                self.dataArray = modes
            }else{
                self.dataArray = modes.suffix(5)
            }
            
            self.showTableView.reloadData()
            for dic in self.dataArray {
                //地震经纬度
                let dzLat = Double(dic["EPI_LAT"] as! String) ?? 0.00
                let dzLon = Double(dic["EPI_LON"] as! String) ?? 0.00
                let location = CLLocationCoordinate2D(latitude: dzLat, longitude: dzLon)
                let pointAnnotation = MKPointAnnotation()
                pointAnnotation.coordinate = location
                pointAnnotation.title = "\(dic["M"] as? String ?? "")级"
                pointAnnotation.subtitle = dic["LOCATION_C"] as? String ?? ""
                self.appleMapView.addAnnotation(pointAnnotation)
                self.appleMapView.selectAnnotation(pointAnnotation, animated: true)
                self.appleMapView.centerCoordinate = location
                
                let initialRegion = MKCoordinateRegion(
                    center: location,
                    span: MKCoordinateSpan(latitudeDelta: 0.8, longitudeDelta: 0.8))
                self.appleMapView.region = initialRegion
                
                // 设置圆形范围
                let shendu = (Double(dic["EPI_DEPTH"] as? String ?? "00") ?? 0.00) * 1000
                let circle = MKCircle(center: location, radius: shendu)
                self.appleMapView.addOverlay(circle)
            }
        } failure: { task, error in
            
        }
        
    }
    
    func parseHTMLWithSwiftSoup(html: String) {
        dataArray.removeAll()
        do {
            var tempArray = [[String:Any]]()
            let doc = try SwiftSoup.parse(html)
            // 查找所有的 <li> 标签
            let lis = try doc.select("li")
            var dataDic = [String:Any]()
            for li in lis.array() {
                var liHtml = ""
                let liClass = try li.attr("class")
                if liClass == "lsdz_list" {
                    liHtml = try li.outerHtml()
                    
                    let lidoc = try SwiftSoup.parse(liHtml)
                    // 查找所有的 <span> 标签
                    let spans = try lidoc.select("span")
                    for span in spans.array() {
                        let spanClass = try span.attr("class")
                        if spanClass == "span1" {
                            DLog(message: "span1==\(try span.text())")
                            dataDic["M"] = try span.text()
                        }
                        if spanClass == "span2" {
                            DLog(message: "span2==\(try span.text())")
                            dataDic["O_TIME"] = try span.text()
                        }
                        if spanClass == "span3" {
                            DLog(message: "span3==\(try span.text())")
                            dataDic["EPI_LON"] = try span.text()
                        }
                        if spanClass == "span4" {
                            DLog(message: "span4==\(try span.text())")
                            dataDic["EPI_LAT"] = try span.text()
                        }
                        if spanClass == "span5" {
                            DLog(message: "span5==\(try span.text())")
                            dataDic["EPI_DEPTH"] = try span.text()
                        }
                        if spanClass == "span6" {
                            DLog(message: "span6==\(try span.text())")
                            dataDic["LOCATION_C"] = try span.text()
                        }
                    }
                    
                    tempArray.append(dataDic)
                }
            }
            
            for i in 0 ..< tempArray.count {
                if i < 5 {
                    self.dataArray.insert(tempArray[i], at: 0)
                }
            }
            
            DLog(message: "dataArray==\(self.dataArray)")
            
            self.showTableView.reloadData()
            for dic in self.dataArray {
                //地震经纬度
                let dzLat = Double(dic["EPI_LAT"] as! String) ?? 0.00
                let dzLon = Double(dic["EPI_LON"] as! String) ?? 0.00
                let location = CLLocationCoordinate2D(latitude: dzLat, longitude: dzLon)
                let pointAnnotation = MKPointAnnotation()
                pointAnnotation.coordinate = location
                pointAnnotation.title = "\(dic["M"] as? String ?? "")级"
                pointAnnotation.subtitle = dic["LOCATION_C"] as? String ?? ""
                self.appleMapView.addAnnotation(pointAnnotation)
                self.appleMapView.selectAnnotation(pointAnnotation, animated: true)
                self.appleMapView.centerCoordinate = location
                
                let initialRegion = MKCoordinateRegion(
                    center: location,
                    span: MKCoordinateSpan(latitudeDelta: 0.8, longitudeDelta: 0.8))
                self.appleMapView.region = initialRegion
                
                // 设置圆形范围
                let shendu = (Double(dic["EPI_DEPTH"] as? String ?? "00") ?? 0.00) * 1000
                let circle = MKCircle(center: location, radius: shendu)
                self.appleMapView.addOverlay(circle)
            }
        } catch {
            print("Parsing error: \(error.localizedDescription)")
        }
    }
}

extension DZhHomeController{
    
    func refreshData(withTabelViewTag tableViewTag: Int) {
        self.getListData()
    }
    
    func loadMoreData(withTabelViewTag tableViewTag: Int) {
        self.getListData()
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return pixw(p: 40)
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let bgView = UIView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: pixw(p: 40)))
        let headLabel = UILabel(frame: CGRect(x: pixw(p: 15), y: pixw(p: 20), width: pixw(p: 300), height: pixw(p: 20)))
        headLabel.text = LocalizedString("最新地震点")
        bgView.addSubview(headLabel)
        headLabel.textColor = MYBlock
        headLabel.font = MY_SCALE_BoldFont(16)
        
        let moreBtn = UIButton(type: .custom)
        moreBtn.setTitle("查看更多 >", for: .normal)
        moreBtn.setTitleColor(MYColor.color(withHexString: "888888"), for: .normal)
        moreBtn.titleLabel?.font = MY_SCALE_RegularFONT(12)
        bgView.addSubview(moreBtn)
        moreBtn.addGestureRecognizer(UITapGestureRecognizer(actionBlock: { sender in
            let controller = LiShiController()
            self.navigationController?.pushViewController(controller, animated: true)
        }))
        moreBtn.snp.makeConstraints { make in
            make.right.equalTo(pixw(p: -15))
            make.centerY.equalTo(headLabel)
        }
        return bgView
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataArray.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let dic = dataArray[dataArray.count - indexPath.row - 1]
        let cell = tableView.dequeueReusableCell(withIdentifier: "HomeCell") as! HomeCell
        cell.updata(dic: dic, index: indexPath.row)
        if MYGlobal.share().isVip() == false && indexPath.row < 2{
            cell.bgView.viewWithTag(blurEffectTag)?.isHidden = false
        }else{
            cell.bgView.viewWithTag(blurEffectTag)?.isHidden = true
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let flag = MYGlobal.share().isVip()
        if(flag == false){
            Helper.alertShow(withTitle: LocalizedString("提示"), withContent: LocalizedString("您不是VIP会员，暂时无法使用该功能！点击去开通解锁该功能！"), withSureBtnTitle: LocalizedString("去开通"), withCancelBtnTitle: LocalizedString("取消")) { index in
                //去往购买中心
                if index == 1 {
                    let controller = PayMarkController()
                    self.navigationController?.pushViewController(controller, animated: true)
                }
            }
            return
        }
        let dic = dataArray[dataArray.count - indexPath.row - 1]
        let controller = MapDetailController()
        controller.dic = dic
        self.navigationController?.pushViewController(controller, animated: true)
        
    }
    
    func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
        if annotation is MKPointAnnotation{
            let identifier = "CustomAnnotationView"
            var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier)
            if annotationView == nil {
                annotationView = MKMarkerAnnotationView(annotation: annotation, reuseIdentifier: identifier)
                annotationView?.canShowCallout = true
                
                // 创建一个自定义按钮作为右侧的附属视图
                let rightButton = UIButton(type:.detailDisclosure)
                rightButton.setImage(UIImage(named: "comm_right"), for: .normal)
                annotationView?.rightCalloutAccessoryView = rightButton
            } else {
                annotationView?.annotation = annotation
            }
            return annotationView
            
        }
        return nil
    }
    
    
    func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
        DLog(message: "走这里")
        if view.annotation is MKPointAnnotation{
            let flag = MYGlobal.share().isVip()
            if(flag == false){
                Helper.alertShow(withTitle: LocalizedString("提示"), withContent: LocalizedString("您不是VIP会员，暂时无法使用该功能！点击去开通解锁该功能！"), withSureBtnTitle: LocalizedString("去开通"), withCancelBtnTitle: LocalizedString("取消")) { index in
                    //去往购买中心
                    if index == 1 {
                        let controller = PayMarkController()
                        self.navigationController?.pushViewController(controller, animated: true)
                    }
                }
                return
            }
            let title = view.annotation!.title
            let subTitle = view.annotation!.subtitle
            for dic in self.dataArray {
                let tempTitle = "\(dic["M"] ?? "")级"
                let tempSubTitle = "\(dic["LOCATION_C"] ?? "")"
                if title == tempTitle && tempSubTitle == subTitle {
                    let controller = MapDetailController()
                    controller.dic = dic
                    self.navigationController?.pushViewController(controller, animated: true)
                    return
                }
            }
        }
    }
    
    func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
        if overlay is MKCircle{
            let cirleRender = MKCircleRenderer(overlay: overlay)
            cirleRender.lineWidth = 2
            cirleRender.strokeColor = MYColor.color(withHexString: "#E04148", alpha: 0.2)
            cirleRender.fillColor = MYColor.color(withHexString: "#999999", alpha: 0.2)
            return cirleRender
        }
        return MKOverlayRenderer()
    }
}






